#coding=utf-8
# revision_filter_window.py - Modal Window to set revision filter.
#
# Copyright 2011 Paul Gluchow <pgsurp@googlemail.com>
# Copyright 2012 Kirill Gagarski <gagarin.gtn@gmail.com>
# Copyright 2012 Maxim Petrov <maximpetrov@yahoo.com>

# This software may be used and distributed according to the terms of the
# GNU General Public License version 3.

from modal_window import ModalWindow
from controls import TextField, TextArea, Button, Label, CheckBox
import curses.ascii

class RevisionFilterWindow(ModalWindow):
    """
    modal window class for setting filter options to current revision list
    """
    _PREFERRED_MIN_WIDTH = 40
    _PREFERRED_MIN_HEIGHT = 14
    _MIN_WIDTH = 25
    _MIN_HEIGHT = 14
    _SHOULD_ENLARGE = False
    _EXIT_BUTTON = u'Cancel'
    _revision_label = _(u'Revision ')
    _hash_label = _(u'Hash ')
    _date_label = _(u'Date ')
    _user_label = _(u'User ')
    _branch_label = _(u'Branch ')
    _bookmarks_label = _(u'Bookmarks ')
    _message_label = _(u'Message ')
    _all_revs_label = _(u'All revisions ')
    _title = _(u'Revision filter')
    # Подписи кнопок
    __OK = _(u'OK')
    __CANCEL = _(u'Cancel')

    def __init__(self):
        """
        Конструктор окна фильтра
        """
        rev_label_len = len(self._revision_label)
        self.__rev_label = Label(None,
            lambda w, h: (2, 2, rev_label_len, None), self._revision_label)
        self.__rev_field = TextField(None, lambda w, h: (rev_label_len + 2,
            2, w - rev_label_len - 5 , None))
            
        hash_label_len = len(self._hash_label)
        self.__hash_label = Label(None,
            lambda w, h: (2, 3, hash_label_len, None), self._hash_label)
        self.__hash_field = TextField(None, lambda w, h: (hash_label_len + 2,
            3, w - date_label_len - 5 , None))
        
        date_label_len = len(self._date_label)
        self.__date_label = Label(None,
            lambda w, h: (2, 4, date_label_len, None), self._date_label)
        self.__date_field = TextField(None, lambda w, h: (date_label_len + 2,
            4, w - date_label_len - 5 , None))
        
        user_label_len = len(self._user_label)
        self.__user_label = Label(None,
            lambda w, h: (2, 5, user_label_len, None), self._user_label)
        self.__user_field = TextField(None, lambda w, h: (user_label_len + 2,
            5, w - user_label_len - 5 , None))
        
        branch_label_len = len(self._branch_label)
        self.__branch_label = Label(None,
            lambda w, h: (2, 6, branch_label_len, None), self._branch_label)
        self.__branch_field = TextField(None, lambda w, h: (branch_label_len + 2,
            6, w - branch_label_len - 5 , None))

        bookmarks_label_len = len(self._bookmarks_label)
        self.__bookmarks_label = Label(None,
            lambda w, h: (2, 7, bookmarks_label_len, None), self._bookmarks_label)
        self.__bookmarks_field = TextField(None, lambda w, h: (bookmarks_label_len + 2,
            7, w - bookmarks_label_len - 5 , None))
        
        message_label_len = len(self._message_label)
        self.__message_label = Label(None,
            lambda w, h: (2, 8, message_label_len, None), self._message_label)
        self.__message_field = TextField(None, lambda w, h: (message_label_len + 2,
            8, w - message_label_len - 5 , None))
            
        all_revs_label_len = len(self._all_revs_label)
        self.__all_revs_label = Label(None,
            lambda w, h: (2, 10, all_revs_label_len, None), self._all_revs_label)
        self.__all_revs_box = CheckBox(None, lambda w, h: (all_revs_label_len + 2,
            10, w - all_revs_label_len - 5 , None))

        self.__ok_button = Button(None, lambda w, h: \
            (w / 4 - len(self.__OK) / 2, h - 2, None, None), self.__OK)
        self.__cancel_button = Button(None, lambda w, h: \
            (w * 3 / 4 - len(self.__CANCEL) / 2, h - 2, None, None), self.__CANCEL)

        self._controls = [(self.__rev_field, True), (self.__rev_label, False),
                           (self.__hash_field, True), (self.__hash_label, False),
                           (self.__date_field, True), (self.__date_label, False),
                           (self.__user_field, True), (self.__user_label, False),
                           (self.__branch_field, True), (self.__branch_label, False),
                           (self.__bookmarks_field, True), (self.__bookmarks_label, False),
                           (self.__message_field, True), (self.__message_label, False),
                           (self.__all_revs_box, True), (self.__all_revs_label, False),
                           (self.__ok_button, True), (self.__cancel_button, True)]

    def handle_keypress(self, ch, uni):
        """
        Функция отрабатывает нажатие клавиши.

        Аргументы:
            ch - код нажатой клавиши
            uni - признак того, что ch - является символом в юникоде

        """

        result = ModalWindow.handle_keypress(self, ch, uni)
        if result is not None:
            return result
        # По нажатию табуляции переходим к следующему элементу управления
        if ch == ord('\t'):
            self._next_control()
        elif ch == curses.KEY_UP and self._selected not in (self.__rev_field,
                                                            self.__ok_button,
                                                            self.__cancel_button):
            self._previous_control()
        elif ch == curses.KEY_DOWN and self._selected not in (self.__all_revs_box,
                                                              self.__ok_button,
                                                              self.__cancel_button):
            self._next_control()
        elif ch == ord('\n'):
            # Если нажат Enter где угодно кроме Cancel, то возвращаем OK
            # вместе с содержимым полей.
            if self._selected == self.__cancel_button:
                return {u'button': u'Cancel'}
            else:
                return {u'button': u'OK',
                        _(u'rev'): self.__rev_field.text,
                        _(u'hash'): self.__hash_field.text,
                        _(u'date'): self.__date_field.text,
                        _(u'user'): self.__user_field.text,
                        _(u'branch'): self.__branch_field.text,
                        _(u'bookmarks'): self.__bookmarks_field.text,
                        _(u'message'): self.__message_field.text,
                        u'all' : self.__all_revs_box.checked}
        else:
            self._selected.handle_keypress(ch, uni)
